<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Private Inheritance</title>
  <meta
 content="C++ Tutorial: Private Inheritance"
 name="description" />
  <meta
 content="C++ Tutorial, Private Inheritance, Composition"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">

<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>
<br />
<br />
<br />
<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial - Private Inheritance</span></div>
<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>   
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL) I</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>
<br />

<br />
<img src="images/private_inheritance/JangSoo.png" alt="JangSoo"/>
<br />
<br />


<div class="bodytext" style="padding: 12px;" align="justify">
<div class="subtitle" id="private_inheritance">Private Inheritance</div>
<p><strong>Private Inheritance</strong> is one of the ways of implementing the <strong>has-a</strong> relationship. With private inheritance, public and protected member of the base class become private members of the derived class. That means the methods of the base class do not become the public interface of the derived object. However, they can be used inside the member functions of the derived class.</p>
<p>Because there are implications of using private inheritance, in his book, "Effective C++ 55 ...", Scott Meyers gave a separate item for private inheritance: item 39: "Use private inheritance judiciously."<br />
Let's briefly look at the head of that section showing not <strong>is-a</strong> but <strong>has-a</strong> property of private inheritance.</p>
<pre>
class Person {};
class Student:private Person {};	// private
void eat(const Person& p){}		// anyone can eat
void study(const Student& s){}		// only students study

int main() 
{
	Person p;	// p is a Person
	Student s;	// s is a Student
	eat(p);		// fine, p is a Person
	eat(s);		// error! a Student isn't a Person
	return 0;
}
</pre>
<p>He explains,
in contrast to public inheritance, compilers will generally <strong>not</strong> convert a derived class object (<strong>Student</strong>) into a base class object (<strong>Person</strong>) if the inheritance relationship between the classes is private. That's why the call to <strong>eat()</strong> fails for the object <strong>s</strong>.<br />

<br />
<p>With public inheritance, the public methods of the base class become public methods of the derived class. In other words, the derived class <strong>inherits</strong> the base-class <strong>interface</strong>. This is the <strong>is-a</strong> relationship. But with the private inheritance, the public methods of the base class become private methods of the derived class. So, the derived class <strong>does not inherit</strong> the base-class <strong>interface</strong>.</p>
<p>A class <strong>does inherit</strong> the <strong>implementation</strong> with private inheritance.</p>
<p>In his new book, "Programming Principles and Practice Using C++", Stroustrup described the implementation and interface as follows:</br>
The <strong>interface</strong> is the part of the class's declaration that its users access directly. The <strong>implementation</strong> is the part of the class's declaration that its users access only indirectly through the interface.</p> 
<p>Let's look at the following example:</p>
<pre>
#include &lt;iostream&gt;

using namespace std;

class Engine {
 public:
	Engine(int nc){
		 cylinder = nc;
	}

	void start() {
		cout << getCylinder() <<" cylinder engine started" << endl;
	};

	int getCylinder() {
		return cylinder;
	}
	
private:
	int cylinder;
 };
 
 class Car : <font color="blue">private Engine</font> {    // Car has-a Engine
 public:
   Car(int nc = 4) : Engine(nc) { }        
   void start() {
	cout << "car with " << Engine::getCylinder() <<
		   " cylinder engine started" << endl;
	Engine:: start();
   }
 }; 

int main( ) 
{ 
	Car c(8);
	c.start();
	return 0; 
}
</pre>
<p>The output is:</p>
<pre>
car with 8 cylinder engine started
8 cylinder engine started
</pre>
<p>As we see from the example, the <strong>Car</strong> class winds up with an inherited <strong>Engine</strong> component such as <strong>cylinder</strong> and the <strong>Car</strong> method can use the Engine method, <strong>getCylinder()</strong>, internally to access the Engine component, <strong>cylinder</strong>.</p>
<p>In short, private inheritance <strong>does</strong> acquire the <strong>implementation</strong>, but <strong>does not</strong> acquire <strong>interface</strong>.</p>
<br />
<br />

<div class="subtitle_2nd" id="composition">Composition</div>
<p>As you may know, the <strong>private</strong> inheritance is a  variant of <strong>composition</strong>, <strong>aggregation</strong>, or <strong>containment</strong>. So, the <strong>has-a</strong> relationship can be achieved using <strong>composition</strong> as in the example below.</p>
<pre>
#include &lt;iostream&gt;

using namespace std;

class Engine {
 public:
	Engine(int nc){
		 cylinder = nc;
	}

	void start() {
		cout << getCylinder() <<" cylinder engine started" << endl;
	};

	int getCylinder() {
		return cylinder;
	}

private:
	int cylinder;
 };
 
 class Car {
 public:
	Car(int n = 4): eng(n) { }	

	void start() {
	   cout << "car with " << eng.getCylinder() <<
		   " cylinder engine started" << endl;
		eng.start();
	}
private:
	<font color="blue">Engine eng;</font>	// Car has-a Engine
 }; 

int main( ) 
{ 
	Car c(8);
	c.start();
	return 0; 
}
</pre> 
<p>This produced the same output as the example for private inheritance.</p>
<pre>
car with 8 cylinder engine started
8 cylinder engine started
</pre>

<br />
<br />

<div class="subtitle_2nd" id="compositionvsprivate">Composition vs. Private Inheritance</div>
<p>So, what are the similarities and differences between <strong>private inheritance</strong> and <strong>composition</strong>?</p>
<ul>
	<li><strong>Similarities</strong><br />
	<ul>
		<li>In both cases, there is exactly one <strong>Engine</strong> member object contained in every <strong>Car</strong> object.</li> 
		<li>In both cases the <strong>Car</strong> class has a <strong>start()</strong> method that calls the <strong>start()</strong> method on the contained <strong>Engine</strong> object.</li> 
		<li>In neither case can users (outsiders) convert a <strong>Car*</strong> to an <strong>Engine*</strong>.</li> 
	</ul>
	</li>
	<br />
	<li><strong>differences</strong><br />
	<ul>
		<li>The <strong>composition</strong> is needed if you want to contain several <strong>Engine</strong>s per <strong>Car</strong>.</li> 
		<li>The <strong>private inheritance</strong> can introduce unnecessary multiple inheritance.</li> 
		<li>The <strong>private inheritance</strong> allows members of <strong>Car</strong> to convert a <strong>Car*</strong> to an <strong>Engine*</strong>.</li> 
		<li>The <strong>private inheritance</strong> allows access to the <strong>protected</strong> members of the base class.</li> 
		<li>The <strong>private inheritance</strong> allows <strong>Car</strong> to override <strong>Engine</strong>'s <strong>virtual</strong> functions.</li> 
	</ul>
	</li>
</ul>

<br />
<br />

<div class="subtitle_2nd" id="whichone">Which should I prefer: composition or private inheritance?
</div>
<p>Given that we can achieve a <strong>has-a</strong> relationship either with composition or with private inheritance, which should we use? Use <strong>composition</strong> when you can, but use <strong>private</strong> inheritance when you have to. </p>
<p>When we look at the class declaration, we see explicitly named objects representing the contained classes, and our code can refer to these objects <strong>by name</strong>. While the private inheritance makes the relationship seem more abstract. Also, inheritance can raise problems of <strong>multi-inheritance</strong>.</p>
<p>In short, we're less likely to run into trouble if we use composition. Also, as we summarized in the previous section, composition allows us to include <strong>several objects</strong>.</p>
<p>On the other hand, private inheritance does offer features that composition can't. Suppose, for example, that a class has <strong>protected</strong> members. Such members are available to derived classes but not to the world. If we include such a class in another class by using composition, the new class becomes part of that world, not a derived class. So, it can't access protected members. But by using inheritance makes the new class a derived class, so it can access protected members.</p>
<p>Another case that gives private inheritance advantage is if we want to redefine <strong>virtual functions</strong>. This is a privilege awarded to a derived class but not to a containing class.</p>

<br />
<br />

<div class="subtitle_2nd" id="summary">Summary</div>
<p>I'll use Scott Meyers' statements as a summary.<br />
"Private inheritance means <strong>is-implemented-in-terms-of</strong>. If you make a class <strong>D</strong> privately inherit from a class <strong>B</strong>, you do so because you are interested in taking advantage of some of the features available in class <strong>B</strong>, not because there is any conceptual relationship between objects of types <strong>B</strong> and <strong>D</strong>. As such, private inheritance is purely an implementation technique. (That's why everything you inherit from a private base class becomes private in your class: it's all just implementation detail.)<br />
.... <br />
private inheritance means that implementation <strong>only</strong> should be inherited; interface should be ignored. If <strong>D</strong> privately inherits from <strong>B</strong>, it means that <strong>D</strong> objects are implemented in terms of <strong>B</strong> objects, nothing more. Private inheritance means nothing during software <strong>design</strong>, only during software <strong>implementation</strong>."
<div id="rightpanel">
<div align="center">
</div></div>
<br /><br /><br />

<br />

<br />
<img src="images/private_inheritance/JangSoo2.png" alt="JangSoo2"/>
<br />
<br />


<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL) I</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
<br /><br />



<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
